package com.whfc.emp.xxl.job.generateData;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.XxlJobConfig;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.Gps;
import com.whfc.common.util.MathUtil;
import com.whfc.emp.cncit.entity.CncitUpMsgS;
import com.whfc.emp.dao.AppEmpMapper;
import com.whfc.emp.dao.AppFaceGateMapper;
import com.whfc.emp.dao.AppFaceGatePersonMapper;
import com.whfc.emp.dto.AppEmpDTO;
import com.whfc.emp.dto.AppFaceGateDTO;
import com.whfc.emp.entity.AppFaceGate;
import com.whfc.emp.entity.AppFaceGatePerson;
import com.whfc.emp.manager.AppEmpWarnRuleManager;
import com.whfc.emp.manager.AppFaceGateManager;
import com.whfc.emp.param.EmpAttendSyncDataParam;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description 生成人员生成演示数据
 * @Author hw
 * @Date 2021-09-07 11:43
 * @Version 1.0
 */
@Component
@ConditionalOnBean(XxlJobConfig.class)
public class EmpDemoDataGenerateJob {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private AppEmpWarnRuleManager appEmpWarnRuleManager;

    @Autowired
    private AppFaceGatePersonMapper appFaceGatePersonMapper;

    @Autowired
    private AppEmpMapper appEmpMapper;

    @Autowired
    private AppFaceGateManager appFaceGateManager;

    Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 人员设备电量
     */
    private final AtomicInteger empBatteryPower = new AtomicInteger(100);

    /**
     * 生成人员报警以及安全帽数据
     */
    @XxlJob("generateEmpData")
    public void generateEmpData() {
        XxlJobHelper.log("开始生成人员报警以及安全帽数据...");
        logger.info("开始生成人员安全帽，以及报警数据...");
        String paramStr = XxlJobHelper.getJobParam();
        JSONObject param = null;
        if (StringUtils.isEmpty(paramStr)) {
            XxlJobHelper.handleFail("没有配置参数");
            return;
        }
        param = JSONObject.parseObject(paramStr);
        List<Date> dates = new ArrayList<>();
        Date dateNow = new Date();
        if (param.containsKey("time")) {
            Date date = param.getDate("time");
            Date startDate = DateUtil.getDateBegin(date);
            Date enhdDate = DateUtil.getDateEnd(date);
            dates = DateUtil.getDayListOfMinute(startDate, enhdDate, 10);
        } else {
            dates.add(dateNow);
        }
        Random random = new Random();
        List<Integer> list = param.getJSONArray("deviceIds").toJavaList(Integer.class);
        List<Integer> ruleIds = param.getJSONArray("ruleIds").toJavaList(Integer.class);


        for (Date date : dates) {
//            if (!isRunTime(date)) {
//                XxlJobHelper.log("当前不是运行时间");
//                continue;
//            }
            for (int i = 0; i < ruleIds.size(); i++) {
                Integer ruleId =  ruleIds.get(i);
                Double lng = randomLngLat().getLng();
                Double lat = randomLngLat().getLat();
                XxlJobHelper.log("规则Id:"+ruleId+" lng:"+lng+" lat:"+lat);
                appEmpWarnRuleManager.buildEmpWarnData(ruleId, dateNow,lng,lat);
            }
            for (Integer deviceId : list) {
                CncitUpMsgS cncitUpMsgS = new CncitUpMsgS();
                cncitUpMsgS.setDeviceId(deviceId);
                cncitUpMsgS.setTime(DateUtil.addSeconds(date, random.nextInt(60)));
                cncitUpMsgS.setLatFlag("N");
                cncitUpMsgS.setLatWgs84(randomLngLat().getLat());
                cncitUpMsgS.setLngFlag("E");
                cncitUpMsgS.setLngWgs84(randomLngLat().getLng());
                cncitUpMsgS.setSpeed(MathUtil.round(random.nextDouble() * 3, 3));
                cncitUpMsgS.setRotation(random.nextInt(70));
                cncitUpMsgS.setVersion("VER2");
                cncitUpMsgS.setGeoNum(random.nextInt(20));
                cncitUpMsgS.setLevelFactor(MathUtil.round(random.nextDouble(), 2));
                cncitUpMsgS.setRssi(random.nextInt(20));
                cncitUpMsgS.setAlarmValue(0);
                cncitUpMsgS.setAlarmCrash(0);
                cncitUpMsgS.setAlarmSos(0);
                cncitUpMsgS.setAlarmDrop(0);
                cncitUpMsgS.setAlarmDoff(0);
                cncitUpMsgS.setAlarmStill(0);
                cncitUpMsgS.setCardStateValue(8);
                cncitUpMsgS.setPosType(0);
                cncitUpMsgS.setPosState(1);
                cncitUpMsgS.setPosMode(2);
                cncitUpMsgS.setBatterVolt(MathUtil.round(random.nextDouble(), 2) + 3);
                cncitUpMsgS.setBatteryPower(empBatteryPower.get() - random.nextInt(5));
                cncitUpMsgS.setAccelerationX(0);
                cncitUpMsgS.setAccelerationY(0);
                cncitUpMsgS.setAccelerationZ(0);
                try {
                    XxlJobHelper.log("empData:{}", cncitUpMsgS);
                    amqpTemplate.convertAndSend(QueueConst.EMP_HELMET_DATA, JSON.toJSONString(cncitUpMsgS));
                } catch (Exception e) {
                    XxlJobHelper.handleFail("生成设备数据失败. error:" + e.getMessage());
                }
            }
            //电量递减
            empBatteryPower.set(empBatteryPower.get() - 5);
            if (empBatteryPower.get() < 10) {
                empBatteryPower.set(100);
            }
        }
    }


    /**
     * 生成人员刷脸数据
     */
    @XxlJob("generateEmpFaceRecordData")
    public void generateEmpFaceRecordData(){
        logger.info("开始生成人员刷脸记录...");
        String paramStr = XxlJobHelper.getJobParam();
        if (StringUtils.isEmpty(paramStr)) {
            logger.info("未配置项目参数");
            XxlJobHelper.handleFail("没有配置参数");
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(paramStr);
        Integer deptId = jsonObject.getInteger("deptId");

        // 获取人员
        List<AppEmpDTO> appEmpDTOS = appEmpMapper.selectByDeptId(deptId, null);
        Date date = new Date();
        for (AppEmpDTO appEmpDTO : appEmpDTOS) {
            List<AppFaceGatePerson> appFaceGatePeople = appFaceGatePersonMapper.selectByEmpIdList(Arrays.asList(appEmpDTO.getEmpId()));
            if (CollectionUtils.isEmpty(appFaceGatePeople)) {
                logger.info("为获取到人员授权信息empId={},empName={}",appEmpDTO.getEmpId(),appEmpDTO.getEmpName());
                continue;
            }
            // 进
            EmpAttendSyncDataParam dataParamIn = new EmpAttendSyncDataParam();
            dataParamIn.setDeptId(deptId);
            dataParamIn.setPersonGuid(appFaceGatePeople.get(0).getPersonGuid());
            dataParamIn.setDeviceKey(appFaceGatePeople.get(0).getDeviceKey());
            dataParamIn.setShowTime(DateUtil.addMinutes(date,-50));
            dataParamIn.setDirection(1);
            dataParamIn.setEmpId(appEmpDTO.getEmpId());
            dataParamIn.setFaceGateId(appFaceGatePeople.get(0).getFaceGateId());
            dataParamIn.setEmpName(appEmpDTO.getEmpName());
            dataParamIn.setPicture(appEmpDTO.getAvatar());
            dataParamIn.setRecMode(1);
            appFaceGateManager.handleRec(dataParamIn);
            // 出
            EmpAttendSyncDataParam dataParamOut = new EmpAttendSyncDataParam();
            dataParamOut.setDeptId(deptId);
            dataParamOut.setPersonGuid(appFaceGatePeople.get(0).getPersonGuid());
            dataParamOut.setDeviceKey(appFaceGatePeople.get(0).getDeviceKey());
            dataParamOut.setShowTime(DateUtil.addMinutes(date,-5));
            dataParamOut.setDirection(0);
            dataParamOut.setEmpId(appEmpDTO.getEmpId());
            dataParamOut.setFaceGateId(appFaceGatePeople.get(0).getFaceGateId());
            dataParamOut.setEmpName(appEmpDTO.getEmpName());
            dataParamOut.setPicture(appEmpDTO.getAvatar());
            dataParamOut.setRecMode(1);
            appFaceGateManager.handleRec(dataParamOut);
        }


    }

    /**
     * 生成随机经纬度
     *
     * @return 经纬度
     */
    private Gps randomLngLat() {
        //经纬度区间
        double minLat = 34.251515D;
        double maxLat = 34.277193D;
        double minLng = 108.92433D;
        double maxLng = 109.00642D;
        BigDecimal db = new BigDecimal(Math.random() * (maxLng - minLng) + minLng);
        double lon = db.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        db = new BigDecimal(Math.random() * (maxLat - minLat) + minLat);
        double lat = db.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        return new Gps(lat, lon);
    }

    /**
     * 是否是运行时间
     *
     * @param date 时间
     * @return 是否是运行时间
     */
    private boolean isRunTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour < 8 || hour > 18 || hour == 12) {
            return false;
        }
        return true;
    }
}
